from rest_framework.viewsets import ModelViewSet
from aaa import models
from rest_framework import serializers
from aaa.utils.pager import myPageNumberPagination
from rest_framework.response import Response
import json
from django.http import JsonResponse

class userSerializer(serializers.ModelSerializer):
    role_name = serializers.SerializerMethodField()
    class Meta:
        model = models.UserInfo
        fields = ['id','username','password','mobile','email','create_time','mg_state','role_name','ip','MAC']
    def get_role_name(self,row):
        print('get_role_name row', row)
        # ret = row.roles.first().roleName
        ret = [ role.roleName for role in row.roles.all()]
        if len(ret) > 1:
            ret = ', '.join(ret)
            return ret
        # print('user ret',ret)
        if not ret:
            return None
        return ret[0]

class userInfoView(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = userSerializer
    # pagination_class = PageNumberPagination
    authentication_classes = []

    def list(self, request, *args, **kwargs):
        print('args',request._request.GET.get('pagenum'))
        users = models.UserInfo.objects.all()
        pg = myPageNumberPagination()
        xx = pg.paginate_queryset(queryset=users,request=request,view=self)
        ser = userSerializer(instance=xx,many=True)
        ret = {}
        ret['data'] = json.dumps(ser.data)
        # print('ser',len(ret['data']),ret['data'])
        ret['total'] = users.count()
        return JsonResponse(ret)